<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
 * Created on 2012-7-5
 *
 */
class My_Model extends CI_Model {
	var	$tableName		= '';
	var $pk				= '';
	var $_field			= array();
	var $_data			= array();

	var $_error			= 'db error';

    function __construct()
    {
        parent::__construct();
		$cacheFile = realpath(APPPATH).'/tmp/~table.'.$this->tableName.'.php';
		if(file_exists($cacheFile)&&empty($this->_field)){
			$cache = include($cacheFile);
			$this->_field = $cache['fields'];
			if(isset($cache['pk']))$this->pk = $cache['pk'];
		}
    }

	/**
     * 初始化 写数据结构配置文件
	 *
     * @access protected 
     * @return void
     * @throws KoExecption
     */
	function init(){
		if(!empty($this->tableName)){//缓存数据结构
			$dbprefix = $this->db->dbprefix;
			$dbSql = "SHOW COLUMNS FROM ".$dbprefix.$this->tableName;
			$rQuery = $this->db->query($dbSql);
			$cache = array();
			$pks = array();
			foreach ($rQuery->result_array() as $field){
				if(is_object($field)) {
					$field	=	get_object_vars($field);
				}
				$fields[$field['Field']] = $field['Default'];
				if($field['Field']=='create_on'||$field['Field']=='update_on'){
					$fields[$field['Field']] = '';
				}
				
				if( strtolower($field['Key']) == 'pri' ){
					$pks[] = $field['Field'];
				}
			}
			if(count($pks)==1)$pks = $pks[0];
			$cache = array(
				'pk' => $pks,
				'fields'=> $fields,
			);
			
			$file = preg_replace("/^{$dbprefix}(\S+?)/", "\\1", $this->tableName);
			$cacheFile = realpath(APPPATH).'/tmp/~table.'.$file.'.php';
			//if( is_writeable($cacheFile)){
				$content = 'return '.var_export( $cache,true ).";\n";
				$content  = "<?php\n".$content."\n?>";
				file_put_contents( $cacheFile,$content );
			//}
		}
	}
	
	/**
	 * 查询结果
	 * @param array $condition array('where'=>'','order'=>'')
	 * @return array jieguo
	 */
	function find( $condition = array() , $isCount=false){
		if(isset($condition['field'])){//string('title,name,content')
			$this->db->select($condition['field']);
		}
		if(isset($condition['where'])){//array or string("name='Joe' AND status='boss' OR status='active'")
			$this->db->where($condition['where']);
		}
		if(isset($condition['order'])){
			if(is_array($condition['order'])){//array('id'=>'asc','name'=>'desc')
				foreach($condition['order'] as $k=>$valueOder){
					$this->db->order_by($k,$valueOder);
				}
			}elseif(is_string($condition['order'])){//'id desc, name asc'
				$this->db->order_by($condition['order']);
			}
		}
		if(isset($condition['join'])){//array('table'=>'','on'=>'') default left join
			if(is_array($condition['join'])){
				$this->db->join($condition['join']['table'],$condition['join']['on']);
			}
		}
		if(isset($condition['group'])){//array("title", "date") or string "title"
			$this->db->group_by($condition['group']);
		}
		if(isset($condition['like'])){//$array = array('title' => $match, 'page1' => $match, 'page2' => $match);
			$this->db->like($condition['like']);
		}
		if($isCount){
			return $this->db->count_all_results($this->tableName);
		}
		if(isset($condition['limit'])){
			$this->db->limit($condition['limit']);
		}
		if(isset($condition['offset'])){
			$this->db->offset($condition['offset']);
		}
		$query = $this->db->get($this->tableName);
		return $query->result_array();
	}
	
	/**
	 * 根据某个字段查询
	 * @param array or string $field 数组构成的where条件
	 * @param int $limit	
	 * @param int $offset
	 * @return array 结果集
	 */
	function findByField($field, $order=FALSE, $limit=null,$offset=null){
		if ($order) {
			$this->db->order_by($order);
		}
		$query = $this->db->get_where($this->tableName,$field,$limit,$offset);
		return $query->result_array();
	}

	/**
	 * 根据主键查询
	 * @param array or int $prkey	array(1,2,3)or 1
	 * @param array $where 查询附件条件
	 * @return array
	 */
	function findByPk($prkey,$where=null){
		if(empty($prkey)) return null;
		if(!is_array($prkey)){
			$prkey = array($prkey);
		}
		empty($where)?'':$this->db->where($where);
		$query = null;
		$query = count($prkey)>1?$this->db->where_in($this->pk, $prkey)->get($this->tableName):$this->db->get_where($this->tableName,array($this->pk=>$prkey[0]));
		return $query->result_array();
	}

	/**
	 * 根据sql语句查询(封装查询) 查询语句中的问号会自动被查询函数中位于第二个参数位置的数组中的值所替代。
	 * @param string $sql $sql = "SELECT * FROM sometableName WHERE id = ? AND status = ? AND author = ?";
	 * @param array $conArray array(3, 'live', 'Rick')
	 * @return array
	 */
	function findBySql($sql = '',$conArray = array()){
		if(empty($sql)) return null;
		$query = $this->db->query($sql,$conArray);
		return $query->result_array();
	}
	
	function save($data){
		//update
		if(isset($data[$this->pk]) && intval($data[$this->pk])>0){
			$this->_data = $this->create($data,'update');
			if( $this->updateByPk($data[$this->pk]) ) return $data[$this->pk];
		}else{//insert
			unset($data['id']);
			$this->_data = $this->create($data,'insert');
			if ($this->insert()) {
				return $this->db->insert_id();
			}
		}
		return false;
	}

	function create($row,$type="insert"){
		$data = array();
		foreach($this->_field as $_field=>$default){
			if(is_int($_field)){
				$_field = $default;
				$default = null;
			}
			if(isset($row[$_field])){
				$data[$_field] = $_field == 'extra_info'  ? serialize( $row[$_field] ) : $row[$_field];
			}else{
				if($type=='insert')$data[$_field] = $default;
			}
		}
		if(isset($this->_field['updated_at']))
			$data['updated_at'] = time();
		if(isset($this->_field['created_at']))
			$data['created_at'] = time();
		if(isset($this->_field['updated_on'])) 
			$data['updated_on'] = date('Y-m-d H:i:m',time());
		if(isset($this->_field['create_on'])&&$type=='insert'){
			$data['created_on'] = date('Y-m-d H:i:m',time());
		}
		return $data;
	}

	function insert(){
		if(!empty($this->_data)){
			return $this->db->insert($this->tableName, $this->_data);
		}
		return false;
	}

	function update( $where = null ){
		if(!empty($this->_data)){
			return $this->db->update($this->tableName, $this->_data, $where);
		}
		return false;
	}

	function updateByPk($prkey){
		if(!empty($this->_data)){
			return $this->db->update( $this->tableName, $this->_data, array($this->pk => $prkey) );
		}
		return false;
	}
	
	function removeByPks($prkey){
		if(!is_array($prkey)){
			$prkey = array($prkey);
		}
		return $this->db->where_in('id', $prkey)->delete($this->tableName);
	}

	function remove($where){
		return $this->db->where($where)->delete($this->tableName);
	}
}
/* End of file MY_Model.php */
/* Location: ./application/core/MY_Model.php */